package com.example.chain.component;

import cn.hutool.json.JSONUtil;
import com.example.chain.dto.DecisionResult;

/**
 * 决策点统一接口类
 *
 * @author shixiaodong
 * @date 2022-05-26
 */
public abstract class IDecision {
    protected IDecision decision;

    /**
     * 执行决策的方法
     */
    public void makeDecision(DecisionResult result) {
        System.out.println("IDecision ===>" + JSONUtil.toJsonStr(result));
    }

    /**
     * 执行下一个节点
     * Q:如何停止责任链？
     * A:只要不执行该方法就好
     *
     * @param result result
     */
    protected void doNext(DecisionResult result) {
        if (decision != null) {
            decision.makeDecision(result);
        }
    }

    /**
     * 添加下一个节点
     */
    private void next(IDecision decision) {
        this.decision = decision;
    }

    /**
     * 采用建造者模式构建链
     */
    public static class Builder {
        /**
         * 头节点
         */
        private IDecision head;
        /**
         * 尾节点
         */
        private IDecision tail;

        public Builder add(IDecision decision) {
            if (this.head == null) {
                this.head = this.tail = decision;
                return this;
            }
            this.tail.next(decision);
            this.tail = decision;
            return this;
        }

        public IDecision build() {
            return this.head;
        }
    }
}
